package com.xsjl.spit.service;


import com.xsjl.common.utils.IdWorker;
import com.xsjl.spit.dao.SpitDao;
import com.xsjl.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    public void saveSpit(Spit spit) {
        spit.setId(idWorker.nextId() + "");
        //默认值
        spit.setPublishtime(new Date());//发布时间为当前时间
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态
        spitDao.save(spit);
        //判断是否存在上级id

        if (spit.getParentid() != null && !"".equals(spit.getParentid())) {
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment", 1);
            mongoTemplate.updateFirst(query, update, "spit");
        }
    }

    public List<Spit> findSpit() {
        return spitDao.findAll();
    }

    public Spit findSpitById(String id) {
        return spitDao.findById(id).get();
    }

    public void updateSpit(Spit spit) {
        spitDao.save(spit);
    }

    public void deleteSpitById(String id) {
        spitDao.deleteById(id);
    }

    public Page<Spit> findSpitByParentid(String parentid, int page, int size) {
        PageRequest of = PageRequest.of(page - 1, size);
        return spitDao.findByParentid(parentid, of);
    }

    public void addThumbup(String id) {
        //1.效率较低，先查询，在保存
        /*Spit spit = spitDao.findById(id).get();
        spit.setThumbup((spit.getThumbup() == null? 0:spit.getThumbup()) + 1);
        spitDao.save(spit);*/
        //2.直接修改
        Query query = new Query();

        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, update, "spit");
    }
}
